package com.peng.community.controller;

import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.DiscussPost;
import com.peng.community.entity.Page;
import com.peng.community.entity.User;
import com.peng.community.service.DiscussPostService;
import com.peng.community.service.UserService;
import com.peng.community.service.impl.LikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class HomeController implements CommunityConstant {

    @Autowired
    UserService userService;

    @Autowired
    DiscussPostService postService;

    @Autowired
    LikeService likeService;

    @GetMapping("/index")
    public String home(Model model, Page page,
                       @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        page.setRows(postService.selectDiscussPostRows(0));
        page.setPath("/index?orderMode=" + orderMode); //不要在跳页的时候丢了这个参数
        System.out.println(page.getCurrent());
        System.out.println(page.getOffset());
        //查询所有评论和用户信息，封装到map返回
        List<Map<String, Object>> res = new ArrayList<>();
        List<DiscussPost> discussPosts = postService.selectDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
        for (DiscussPost discussPost : discussPosts) {
            Map<String, Object> data = new HashMap<>();
            data.put("post",discussPost);
            User user = userService.findUserById(discussPost.getUserId());
            data.put("user",user);
//            log.info("用户的id:{}和姓名:{},用户头像的url:{}",user.getId(), user.getUsername(), user.getHeaderUrl());

            Long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
            data.put("likeCount", likeCount);

            res.add(data);
        }
        model.addAttribute("data",res);
        model.addAttribute("orderMode", orderMode);
        //page被自动装入attribute
        return "index";
    }

    //出现错误统一返回此页面
    @GetMapping("/error")
    public String error() {
        return "/error/500";
    }

    @GetMapping("/denied") //权限不足，访问次页面。
    public String getDeniedPage() {
        return "/error/404";
    }
}